package com.guofeng.config;

import com.guofeng.server.UserDetailsServerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author: guofeng
 * @Date: 2021/08/18/10:09
 * @Description:
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 因为我们用密码授权不需要登录了，它内部就需要一个认证管理器
     *
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    private UserDetailsServerImpl userDetailsServer;

    /**
     * 内存中配置一个登陆信息
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存
        /*auth.inMemoryAuthentication()
                //用户名
                .withUser("aa")
                //密码
                .password(passwordEncoder.encode("aa"))
                //权限
                .authorities("sys:admin");*/
        //基于数据库查询
        auth.userDetailsService(userDetailsServer);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭跨站请求伪造
        http.csrf().disable();
        //表单提交
        http.formLogin();
        //所有的请求都需要认证
        http.authorizeRequests().anyRequest().authenticated();
    }
}
